$(function() {
    var $msg = $('#alert-msg'), $fileId = $('#file-id'), $fileName = $('#file-name');
    var autoSave = function(data) {
        $.ajax({
            url: '/doc/save.do',
            method: 'post',
            data: data,
            success: function(rsp) {
                if (parseInt(rsp.err) != 0) {
                    $('#alert-msg').show();
                    $('#msg-content').html(rsp.errMsg || '<strong>警告!</strong>服务器连接失败,请检查网络连接 稍后进行编辑 ... ');
                    return;
                }
                $('#opt-preview').show();
                var docId = rsp.data.fileId;
                $fileId.val(docId);
            },
            error: function() {
                $('#alert-msg').show();
                $('#msg-content').html('<strong>警告!</strong>服务器连接失败,请检查网络连接 稍后进行编辑 ... ');
            }
        });
    };
    var bindEvent = function() {
        // -- 关闭提示信息
        $('#opt-alert-msg').off('click').bind('click', function() {
            $msg.hide();
        });
        $('#opt-edit-new').off('click').bind('click', function() {
            window.location.reload();
        });
        $('#opt-to-list').off('click').bind('click', function() {
            window.location.href = '/';
        });
        $('#opt-preview').off('click').bind('click', function() {
            var docId = $fileId.val();
            if (docId) {
                var url = '/doc/preview.html?docId=' + docId;
                window.open(url);
            } else {
                $('#alert-msg').show();
                $('#msg-content').html('<strong>警告:</strong>该文档尚未保存,或保存失败! ');
            }
        });
    };
    bindEvent();
    var saveData = function(scope) {
        $msg.hide();
        // -- 随时将编写的内容保存并生成文档
        var previewHtml = scope.getPreviewedHTML();
        var mdHtml = scope.getMarkdown();
        var fileName = $fileName.val(), fileId = $fileId.val();
        if (!fileName || fileName.length <= 0) {
            $('#alert-msg').addClass('alert-danger').show();
            $('#msg-content').html('<strong>提示:</strong> 请先输入文件名称!');
            return;
        }
        // -- 将预览的html生成文件； // -- 将md信息保存到数据库中
        var data = { html: previewHtml, md: mdHtml, fileName: fileName, fileId: fileId };
        autoSave({ data: JSON.stringify(data) });
    };
    var editor = editormd("editormd", {
        width: "100%",
        height: 1130,
        path : "/lib/editor.md/lib/",
        htmlDecode: true,
        onchange: function() {
            //saveData(this);
        },
        onload: function() {
            var scope = this;
            // -- 保存信息
            $('#opt-dmt-save').off('click').bind('click', function() {
                saveData(scope);
            });
            $(window).keydown(function(e) {
                console.log(e);
                if (e.keyCode == 83 && e.ctrlKey) {
                    e.preventDefault();
                    saveData(scope);
                }
            });
        }
    });
});